<?php

namespace Mall\Model;

use Common\Model\BaseModel;
use Common\Model\ModelException;

class CartModel extends BaseModel
{
    protected $_auto = [
        ['create_time', 'time', self::MODEL_INSERT, 'function'],
        ['items', 'serialize', self::MODEL_BOTH, 'function'],
    ];

    protected $_validate = [
    ];

    protected $_scope = [
    ];

    public function putIn($uid, $goodsList)
    {
        $cart = D('Cart')->getByUserId($uid);
        if (empty($cart)) {
            $cart = [
                'user_id' => $uid,
                'items' => [],
            ];
        }
        $user = get_user();
        $items = &$cart['items'];
        foreach ($goodsList as $goods) {
            if (!isset($items[$goods['goods_id']])) {
                $items[$goods['goods_id']] = [];
            }
            if (!isset($items[$goods['goods_id']][$goods['sku']])) {
                $specs = D('GoodsSpec')->where([
                        'goods_id' => $goods['goods_id'], 
                        'id' => ['in', explode(';', $goods['sku'])]])->getField('id,name,val', true);
                $sku = D('GoodsSku')->field('id,name,price,wholesale_price')->getByName($goods['sku']);
                $sku['price'] = $user['role'] === '2' ? $sku['wholesale_price'] : $sku['price'];
                unset($sku['wholesale_price']);
                $items[$goods['goods_id']][$goods['sku']] = [
                    'selectedSpecs' => array_values($specs),
                    'selectedSku' => $sku,
                    'quantity' => 0,
                ];
            }
            $items[$goods['goods_id']][$goods['sku']]['quantity'] += $goods['quantity'];
        }

        $cartModel = D('Cart');
        if ($cartModel->create($cart)) {
            isset($cart['id']) ? $cartModel->save() : $cartModel->add();
        }

    }

    /**
     * 移出购物车
     *
     * @param  int $uid 用户ID
     * @param array $goodsList [['goods_id' => xxx, 'quantity' => 121], ['goods_id' => xxx, 'quantity' => 121]]
     * @return void
     */
    public function putOut($uid, $goodsList)
    {
        $cart = D('Cart')->getByUserId($uid);
        if (empty($cart)) return false;
        $items = &$cart['items'];
        foreach ($goodsList as $goods) {
            $items[$goods['goods_id']][$goods['sku']]['quantity'] -= $goods['quantity'];
            if ($items[$goods['goods_id']][$goods['sku']]['quantity'] <= 0) unset($items[$goods['goods_id']][$goods['sku']]);
            if (empty($items[$goods['goods_id']])) unset($items[$goods['goods_id']]);
        }
        $cartModel = D('Cart');
        if ($cartModel->create($cart)) {
            $cartModel->save();
            return true;
        } else {
            return false;
        }
    }



    protected function _after_find(&$record, $options)
    {
        $record['items'] = unserialize($record['items']);
        foreach ($record['items'] as $key => &$value) {
            foreach ($value as $k => &$v) {
            $stock = D('GoodsSku')->field('stock')->where(['name'=>$k])->find();
            $v['selectedSku']['stock'] = $stock['stock'];
            }
        }
    }

    protected function _after_select(&$records, $options)
    {
        foreach ($records as &$record) {
            $this->_after_find($reocrd, $options);
        }

    }
    
}
